package com.happyclub.paul.service.impl;


import com.happyclub.paul.dao.UserRepostitory;
import com.happyclub.paul.service.ILogiinHistoryService;
import com.happyclub.paul.service.IUserService;
import com.happyclub.paul.service.PersonalPhotoAlbumService;
import com.happyclub.paul.service.PhotoAlbumService;
import com.happyclub.pojo.TbPersonalPhotoAlbum;
import com.happyclub.pojo.TbPhotoAlbum;
import com.happyclub.pojo.TbUser;
import com.happyclub.utils.JsonResult;
import com.happyclub.utils.Md5Utits;
import com.happyclub.utils.Uuid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserRepostitory userRepostitory;

    //用户相册中间表
    @Autowired
    private PersonalPhotoAlbumService personalPhotoAlbumService;

    //相册表
    @Autowired
    private PhotoAlbumService photoAlbumService;


    @Autowired
    private ILogiinHistoryService logiinHistoryService;            //登录历史

    /**
     * 判断用户账号密码是否正确
     *
     * @param telephone
     * @param password
     * @return
     */
    @Override
    public JsonResult queryUserExists(String telephone, String password) {

        JsonResult jsonResult = new JsonResult();
        try {
            TbUser user = userRepostitory.findUserByTelephone(telephone);
            //如果手机号不存在，提示用户注册
            if (user == null) {
                jsonResult.setErrorCode("500");
                jsonResult.setMsg("用户不存在");
                return jsonResult;
            }
            System.out.println("密码："+user.getUserPassword());
            //比较密码，如果密码错误
            if (!Md5Utits.EncoderByMd5(password).equals(user.getUserPassword())) {
                jsonResult.setErrorCode("501");
                jsonResult.setMsg("密码错误");
                return jsonResult;
            }
            //表示用户存在
            jsonResult.setErrorCode("OK");
            jsonResult.setMsg("用户已注册，账号密码正确");


            String city = user.getCity();
            String[] strings = city.split("#");

            //将用户登录信息保存登录历史表
            Integer cnt = logiinHistoryService.createLogiinHistory(Uuid.getUUID(), user.getUserId(), "手机", null, strings[0], strings[1]);

            jsonResult.setResult(user);
        } catch (Exception e) {
            jsonResult.setMsg(e.getMessage());
            jsonResult.setErrorCode("error");
            e.printStackTrace();
        }
        return jsonResult;
    }


    /**
     *@Description:  保存用户注册信息
     *@Author: 魏泉琦
     *@date: 2019/4/3
     */
    @Transactional
    @Override
    public JsonResult insertUser(TbUser user) {
        JsonResult jsonResult = new JsonResult();
        try {
            user.setUserId(Uuid.getUUID());         //设置用户UUID
            String md5 = Md5Utits.EncoderByMd5(user.getUserPassword());//加密用户密码
            user.setHeadPortrait("http://47.107.81.116/group1/M00/00/00/rBEN6VyrL6-AGdHuAADwqJDC2So435.jpg");
            Integer cnt = userRepostitory.insertUserMsg(user.getUserId(),user.getNickName(),user.getSex(),user.getTelephone(),user.getHeadPortrait(),user.getAge(),user.getPersonalizedSignature(),user.getHobby(),user.getPost(),user.getHometown(),user.getCity(),user.getEmail(),md5,user.getSolemelber());
            if(cnt==null){
                jsonResult.setMsg("注册失败，请重新注册！！");
                jsonResult.setErrorCode("NO");
                return jsonResult;
            }
        }catch (Exception e){
            jsonResult.setErrorCode("error");
            jsonResult.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return jsonResult;
    }


    /**
     *@Description: 通过注册手机号查询用户信息
     *@Author: 魏泉琦
     *@date: 2019/4/3
     */
    @Override
    public TbUser queryUserByTelephone(String telephone) {
        return userRepostitory.findUserByTelephone(telephone);
    }


    /**
     *@Description: 根据用户编号查询用户信息
     *@Author: 魏泉琦
     *@date: 2019/4/3
     */
    @Override
    public JsonResult queryUserById(String uid) {
        TbUser user = userRepostitory.queryUserById(uid);
        JsonResult jsonResult = new JsonResult();
        if(user==null){
            jsonResult.setErrorCode("500");
            jsonResult.setMsg("用户不存在");
            return  jsonResult;
        }
        jsonResult.setResult(user);
        return jsonResult;
    }

    /**
     *@Description: 通过注册手机号码删除用户
     *@Author: 魏泉琦
     *@date: 2019/4/3
     */
    @Transactional
    @Override
    public Integer deleteUserByTelephone(String telephone) {
        return userRepostitory.deleteUserByTelephone(telephone);
    }

    /**
     *@Description: 通过用户编号删除用户
     *@Author: 魏泉琦
     *@date: 2019/4/3
     */
    @Override
    public Integer deleteUserById(String uid) {
        return userRepostitory.deleteUserById(uid);
    }



    /**
     *@Description: 保存用户修改之后的信息
     *@Author: 魏泉琦
     *@date: 2019/4/3
     */
    @Transactional
    @Override
    public JsonResult saveUpdateUserMsg(TbUser user) {
        JsonResult jsonResult = new JsonResult();
        Integer cnt = userRepostitory.updateUserMsg(user.getNickName(), user.getSex(), user.getHeadPortrait(), user.getAge(), user.getPersonalizedSignature(), user.getHobby(), user.getPost(), user.getHometown(), user.getCity(), user.getEmail(), user.getUserPassword(), user.getTelephone());
        if(cnt<=0){          //修改信息失败
            jsonResult.setMsg("修改失败，请稍后尝试");
            jsonResult.setErrorCode("NO");
            return jsonResult;
        }
        return jsonResult;
    }


    /**
     *@Description: 查询指定用户拥有的所有相册
     *@Author: 魏泉琦
     *@date: 2019/4/6
     */
    @Override
    public JsonResult showUserPhotoAlbum(String userId) {
        JsonResult jsonResult = new JsonResult();

        List<TbPersonalPhotoAlbum> photoAlbums = personalPhotoAlbumService.showUserPhotoAlbum(userId);      //该集合包含了该用户的所有相册编号
        if(photoAlbums==null){
            jsonResult.setErrorCode("500");
            jsonResult.setMsg("您还未创建相册");
            return jsonResult;
        }

        TbUser user  = new TbUser();
        List<TbPhotoAlbum> tbPhotoAlbums = new ArrayList<>();

        for (TbPersonalPhotoAlbum photoAlbum: photoAlbums) {                   //循环集合photoAlbums，查询出相册的信息
            TbPhotoAlbum tbPhotoAlbum = photoAlbumService.queryPhotoAlbumsById(photoAlbum.getPhotoAlbumId());
            tbPhotoAlbums.add(tbPhotoAlbum);
        }
        user.setUserId(userId);
        user.setPhotoAlbums(tbPhotoAlbums);         //将该用户对应的所有相册放入到TbUser对象中
        jsonResult.setMsg("已经查询出该用户所有相册信息");
        jsonResult.setResult(user);
        return jsonResult;
    }

    /**
     *@Description: 查询所有注册用户的信息
     *@Author: 魏泉琦
     *@date: 2019/4/12
     */
    @Override
    public JsonResult queryUsers() {
        JsonResult jsonResult = new JsonResult();
        try{
            List<TbUser> users = userRepostitory.findAll();
            if(null == users || users.size()==0){
                jsonResult.setMsg("暂无用户");
                jsonResult.setErrorCode("NO");
                return jsonResult;
            }

        }catch (Exception e){
            jsonResult.setMsg(e.getMessage());
            jsonResult.setErrorCode("error");
            e.printStackTrace();
            return jsonResult;
        }


        return null;
    }


}